/*
 * Copyright 2006 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.note;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import bw.util.*;

public class NoteServlet extends HttpServlet
{
    public static final String ACTION = "action";
    public static final String ID = "id";
    public static final String GET_NOTES = "getNotes";
    public static final String SAVE_NOTE = "save";
    public static final String DELETE_NOTE = "delete";
    public static final String NOTE_ID = "noteId";
    public static final String NOTE_DATA = "data";
    public static final String NOTE_YEAR = "year";
    public static final String NOTE_MONTH = "month";
    public static final String NOTE_DATE = "date";
    public static final String NOTE_HEIGHT = "height";
    public static final String NOTE_WIDTH = "width";
    public static final String NOTE_TOP = "top";
    public static final String NOTE_LEFT = "left";
    public static final String SORT_BY_LASTMOD = "sortByLastMod";

    public void doGet ( HttpServletRequest req, HttpServletResponse res ) 
        throws ServletException, IOException
    {
        String action = req.getParameter( ACTION );
        String name = req.getParameter( ID );

        NoteManager manager = new NoteManager( name );

        res.setContentType( "text/xml" );

        PrintWriter out = res.getWriter();
         
        Vector notes = new Vector();

        String savedNoteId = null;

        if ( GET_NOTES.equals( action ) )
        {
            notes = manager.getNotes();
        }
        else if ( SAVE_NOTE.equals( action ) )
        {
            Note note = getNote( req, manager );

            note.modified();

            try
            {
                //store the updated note
                manager.storeNotes();
            }
            catch ( NoteException ex )
            {
                ex.printStackTrace();
            }

            savedNoteId = note.getId();

            //send back all the notes since we could be reordering
            //the notes based on date.
            notes = manager.getNotes();
        }
        else if ( DELETE_NOTE.equals( action ) )
        {
            Note note = getNote( req, manager );

            try
            {
                manager.deleteNote( note );
            }
            catch ( NoteException ex )
            {
                ex.printStackTrace();
            }

            notes.addElement( note );
        }

        if ( Util.isNonEmpty( req.getParameter( SORT_BY_LASTMOD ) ) )
        {
            Collections.sort( notes, new LastModComparator() );
        }

        if ( savedNoteId != null )
        {
            out.println( "<notes savedNoteId=\"" + savedNoteId + "\">" );
        } 
        else
        {
            out.println( "<notes>" );
        }

        for ( Enumeration e = notes.elements(); e.hasMoreElements(); )
        {
            Note note = (Note) e.nextElement();
            out.println( note.toXML() );
        }

        out.println( "</notes>" );

        out.close();
    }

    /*
    private String replaceURLs ( String data )
    {
        String newData = data;

        int urlStart = -1;
        
        while ( ( urlStart = newData.indexOf( "{http://", urlStart ) ) > -1 )
        {
            int urlEnd = newData.indexOf( "}", urlStart );

            String url = newData.substring( urlStart + 1, urlEnd );

            String link = "<a target=_blank class=\"noteLink\" href=\"" + url + "\">" + url + "</a>";

            newData = newData.substring( 0, urlStart ) + link + newData.substring( urlEnd + 1 );

            urlStart = urlStart + link.length();
        }

        return newData;
    }
    */

    private Note getNote ( HttpServletRequest req, NoteManager manager )
    {
        String id = req.getParameter( NOTE_ID );
        String year = req.getParameter( NOTE_YEAR );
        String month = req.getParameter( NOTE_MONTH );
        String date = req.getParameter( NOTE_DATE );
        String data = req.getParameter( NOTE_DATA );

        String height = req.getParameter( NOTE_HEIGHT );
        String width = req.getParameter( NOTE_WIDTH );
        String top = req.getParameter( NOTE_TOP );
        String left = req.getParameter( NOTE_LEFT );

        Note note = null;
        if ( Util.isNonEmpty( id ) )
        {
            note = manager.getNote( id );
        }
        else
        {
            if ( Util.isNonEmpty( year ) && Util.isNonEmpty( month ) && 
                 Util.isNonEmpty( date ) )
            {
                DateFactory df = DateFactory.getInstance();
                GregorianCalendar cal = df.getCalendar( Integer.parseInt( year ),
                                                        Integer.parseInt( month ),
                                                        Integer.parseInt( date ) );
                
                note = manager.createNote( cal.getTime() );
            }
            else
            {
                note = manager.createNote();
            }
        }
        
        if ( Util.isNonEmpty( height ) && Util.isNonEmpty( width ) &&
             Util.isNonEmpty( top ) && Util.isNonEmpty( left ) )
        {
            try
            {
                note.setHeight( Integer.parseInt( height ) );
                note.setWidth( Integer.parseInt( width ) );
                note.setTop( Integer.parseInt( top ) );
                note.setLeft( Integer.parseInt( left ) );
            }
            catch ( NumberFormatException ex )
            {
                Log.getInstance().write( "Problem parsing note region params!", ex );
            }
        }

        note.setText( data );

        return note;
    }

    class LastModComparator implements Comparator
    {
        public int compare ( Object obj1, Object obj2 )
        {
            Long a = new Long( ( (Note) obj1 ).getLastModified() );
            Long b = new Long( ( (Note) obj2 ).getLastModified() );

            return a.compareTo( b );
        }
    }

}
